import 'package:flutter/services.dart';
import 'dart:convert';

typedef ScanCallback = void Function(String code);

class ScanListener {
  bool enabled = false;

  final ScanCallback scanCallback;
  final int scanEndKeyCode;
  List<int> codeUnits = [];

  ScanListener(
    this.scanCallback, {
    this.scanEndKeyCode = 66,
  }) {
    RawKeyboard.instance.addListener(keyBoardCallback);
    enabled = true;
  }

  keyBoardCallback(RawKeyEvent keyEvent) {
    if (!enabled) return;

    var data = keyEvent.data as RawKeyEventDataAndroid;

    if (keyEvent is RawKeyUpEvent && data.keyCode == scanEndKeyCode) {
      if (codeUnits.isNotEmpty) {
        final barcode = utf8.decode(codeUnits);
        scanCallback(barcode);
        codeUnits.clear();
      }
      return;
    }

    if (keyEvent is RawKeyDownEvent &&
        data.codePoint != 0 &&
        data.codePoint != 10) {
      codeUnits.add(data.codePoint);
    }
  }

  void dispose() {
    RawKeyboard.instance.removeListener(keyBoardCallback);
  }
}
